<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
class Info extends \app\admin\controller\Admin{
    public $modelid,$catid,$cat,$ModelInfo;
    public function __construct(\think\App $app) {
        parent::__construct($app);
        //获取catid
        $catid=Request::param('catid',0,"intval");
        $this->cat= $GLOBALS['cat'][$catid];
        View::assign("cat",$this->cat);
        $this->catid=$catid;
        if(!$this->cat){
            $this->error("栏目信息不存在");
        }
        //获取顶级栏目catid
        preg_match("/\|(\d+)\|*/", $this->cat['parent_catids'],$matches);
        $this->topCatid=$matches[1]?$matches[1]:$this->catid;//如果没有找到顶级栏目id，那说明自己就是顶级栏目
        //
        $this->modelid=$this->cat["modelid"];
        $this->ModelInfo=$GLOBALS["model"][$this->modelid];
        View::assign("ModelTemp","../app/data/modelTemp/".$this->modelid.".php");
        //当前模型，用于调用里面的方法
        $this->model=new \app\admin\model\InfoModel();
        //路由模型
        $this->RouteModel=new \app\admin\model\RouteModel();
        //切换后缀
        $this->model->setSuffix($this->cat["table_name"]);
        //
        $this->model->ModelInfo=$this->ModelInfo;//向模型里注入当前的模型表信息
        $this->model->cat=$this->cat;//向模型里注入当前的栏目信息
        //对应的模型的模型
        $this->ModelModel=new \app\admin\model\ModelModel();
        //数据库字段表
        $this->TableFieldModel=new \app\admin\model\TableFieldModel();
        $this->validate=new \app\admin\validate\InfoValidate();
        //内容模板
        $view_where['type']="view";
        $viewtemp=Db::name("template")->where($view_where)->order("sort asc,template_id desc")->select();
        View::assign("viewtemp",$viewtemp);
        //模型表单路径
        $this->ModelViewPath=app_path()."view/info/model_".$this->modelid."/";
        //各种状态下的数据统计
        View::assign("DataCount",[
            "index"=>$this->model->where([['catid',"IN",getSonCat($this->catid)],['state','=','0']])->count(),//主表
            "Published"=>$this->model->where([['catid',"IN",getSonCat($this->catid)],['state','=','1']])->count(),//主表
            "readyCheck"=>Db::name("cms_cache")->where([['catid',"IN",getSonCat($this->catid)],["state","=","readyCheck"]])->count(),//待审核
            "notCheck"=>Db::name("cms_cache")->where([['catid',"IN",getSonCat($this->catid)],["state","=","notCheck"]])->count(),//被退回
            "draft"=>Db::name("cms_cache")->where([['catid',"IN",getSonCat($this->catid)],["state","=","draft"]])->count(),//草搞
            "recycle"=>Db::name("cms_cache")->where([['catid',"IN",getSonCat($this->catid)],["state","=","recycle"]])->count(),//回收站
            "to_publish"=>Db::name("cms_cache")->where([['catid',"IN",getSonCat($this->catid)],["state","=","to_publish"]])->count(),//回收站
        ]);
    }
    //列表
    public function index(){
        $state=Request::param('state',"0");
        View::assign("state",$state);
       //判断是否在用户勾选权限内[超级管理员不做验证]
        if(!check_user_cat("info_view",$this->catid)){
            $this->error("您没有权限查看此栏目！","Index/console");
        }
        //
        $where=[];
        $where[]=['catid',"IN",getSonCat($this->catid)];
        $where[]=['modelid','=',$this->modelid];
        //分类
        $this->catOption=$this->getCat($this->topCatid);
        $this->catOption="<option value='{$this->topCatid}'>{$GLOBALS['cat'][$this->topCatid]['name']}</option>".$this->catOption;
        View::assign("catOption",$this->catOption);
        //is_top
        $is_top=Request::param('is_top',0,"intval");
        if($is_top){
            $where[]=['is_top',">=",1];
        }
        //is_good
        $is_good=Request::param('is_good',0,"intval");
        if($is_good){
            $where[]=['is_good',">=",1];
        }
        //缩略图
        $thumb=Request::param('thumb');
        if($thumb){
            $where[]=['thumb',"<>",""];
        }
        $state=Request::param('state');
        if($state){
            $where[]=['state',"=","1"];
        }else{
            $where[]=['state',"=","0"];
        }
        //按指定字段搜索
        $searchField=Request::param('searchField');
        $keywords=Request::param('keywords','','trim');
        $searchFilter=Request::param('searchFilter');
        if($searchField&&$keywords&&$searchFilter){
            if($searchFilter=="notlike"){
                $where[]=[$searchField,'NOT LIKE','%'.$keywords.'%'];
            }
            elseif($searchFilter=="all"){
                $where[]=[$searchField,'=',$keywords];
            }
            elseif($searchFilter=="eq"){
                $where[]=[$searchField,'=',$keywords];
            }
            elseif($searchFilter=="neq"){
                $where[]=[$searchField,'<>',$keywords];
            }
            elseif($searchFilter=="gt"){
                $where[]=[$searchField,'>',$keywords];
            }
            elseif($searchFilter=="egt"){
                $where[]=[$searchField,'>=',$keywords];
            }
            elseif($searchFilter=="lt"){
                $where[]=[$searchField,'<',$keywords];
            }
            elseif($searchFilter=="elt"){
                $where[]=[$searchField,'<=',$keywords];
            }
            else{
                $where[]=[$searchField,'LIKE','%'.$keywords.'%'];
            }
        }
        //时间段
        $start_time = Request::param("start_time");
        $end_time = Request::param("end_time");
        if($start_time || $end_time){
            $start_time = strtotime($start_time ? $start_time : 0);
            $end_time = strtotime(($end_time ? $end_time : date("Y-m-d"))."23:59:59");
            $where[]=["addtime","between",[$start_time,$end_time]];
        }
        //查询与分页
        $listRows=Request::param("listRow")?Request::param("listRow"):config("app.page_show_line");//每页显示多少条
        $order=$this->cat["reorder"]?$this->cat["reorder"]:"sort asc,is_top desc,is_good desc,newstime desc,id desc";//默认排序方式
        $data=$this->model->where($where)->order($order)->paginate(['list_rows'=>$listRows,'query' => request()->param()]);
        // 获取分页显示
        $pagelist = $data->render();
        View::assign("pagelist",$pagelist);

        //数据再处理
        foreach($data as $key=>$v){
            //栏目名称d
            $data[$key]['cat']=$GLOBALS["cat"][$v['catid']];
            $data[$key]['has_temp'] = Db::name('cat')->where('catid', $v['catid'])->value('viewtemp');

        }
        View::assign("data",$data);
        if(Request::param('openSearch')){
            //搜索字段
            $SearchFieldInc=$this->TableFieldModel->where([["table_id","=",$this->ModelInfo['table_id']],["issystem","=",1],["field","not in","newstime"]])->field("field,name")->order("sort asc,field_id asc")->select()->toArray();
            $SearchFieldInc[]=["field"=>"username","name"=>"用户"];
            $SearchFieldInc[]=["field"=>"id","name"=>"id"];
            View::assign("SearchFieldInc",$SearchFieldInc);
        }
        //判断是否有自定义列表模板
        if(file_exists($this->ModelViewPath."index.html")){
            return View::fetch($this->ModelViewPath."index.html");
        }else{
            return View::fetch();
        }
    }
    //列表
    public function index_cache(){
        $this->model->setSuffix("cache");//切换后缀
       //判断是否在用户勾选权限内[超级管理员不做验证]
        if(!check_user_cat("info_view",$this->catid)){
            $this->error("您没有权限查看此栏目！","Index/console");
        }
        //
        $state=Request::param('state',"readyCheck");
        View::assign("state",$state);
        //
        $where=[];
        $where[]=['catid',"IN",getSonCat($this->catid)];
        $where[]=['modelid','=',$this->modelid];
        //分类
        $this->catOption=$this->getCat($this->topCatid);
        $this->catOption="<option value='{$this->topCatid}'>{$GLOBALS['cat'][$this->topCatid]['name']}</option>".$this->catOption;
        View::assign("catOption",$this->catOption);
        //状态
        if($state){
            $where[]=['state',"=",$state];
        }
        //按指定字段搜索
        $searchField=Request::param('searchField');
        $keywords=Request::param('keywords','','trim');
        $searchFilter=Request::param('searchFilter');
        if($searchField&&$keywords&&$searchFilter){
            if($searchFilter=="notlike"){
                $where[]=[$searchField,'NOT LIKE','%'.$keywords.'%'];
            }
            elseif($searchFilter=="all"){
                $where[]=[$searchField,'=',$keywords];
            }
            elseif($searchFilter=="eq"){
                $where[]=[$searchField,'=',$keywords];
            }
            elseif($searchFilter=="neq"){
                $where[]=[$searchField,'<>',$keywords];
            }
            elseif($searchFilter=="gt"){
                $where[]=[$searchField,'>',$keywords];
            }
            elseif($searchFilter=="egt"){
                $where[]=[$searchField,'>=',$keywords];
            }
            elseif($searchFilter=="lt"){
                $where[]=[$searchField,'<',$keywords];
            }
            elseif($searchFilter=="elt"){
                $where[]=[$searchField,'<=',$keywords];
            }
            else{
                $where[]=[$searchField,'LIKE','%'.$keywords.'%'];
            }
        }
        //查询与分页
        $listRows=Request::param("listRow")?Request::param("listRow"):config("app.page_show_line");//每页显示多少条
        $order="cache_id desc";//默认排序方式
        $data=$this->model->where($where)->order($order)->paginate(['list_rows'=>$listRows,'query' => request()->param()]);
        // 获取分页显示
        $pagelist = $data->render();
        View::assign("pagelist",$pagelist);
        //数据再处理
        foreach($data as $key=>$v){
            foreach(json_decode($v['data'])->index as $k=>$rs){
                if($rs){
                    $data[$key][$k]=$rs;
                }
            }
            //栏目名称
            $data[$key]['cat']=$GLOBALS["cat"][$v['catid']];
        }
        View::assign("data",$data);
        //
        $SearchFieldInc[]=["field"=>"title","name"=>"标题"];
        $SearchFieldInc[]=["field"=>"id","name"=>"id"];
        $SearchFieldInc[]=["field"=>"username","name"=>"用户"];
        View::assign("SearchFieldInc",$SearchFieldInc);
        //判断是否有自定义列表模板
        if(file_exists($this->ModelViewPath."index_cache.html")){
            return View::fetch($this->ModelViewPath."index_cache.html");
        }else{
            return View::fetch();
        }
    }
    //预览数据
    public function view(){
        $id=Request::param("id",0,"intval");
        $cache_id=Request::param("cache_id",0,"intval");
        if($cache_id){
            $cache=Db::name("cms_cache")->find($cache_id);
            $cache= json_decode($cache['data'],true);
            $r=array_merge($cache['index'],$cache['data']);
        }elseif($id){
            $index=Db::name("cms_".$this->ModelInfo["table_name"])->find($id);
            $data=Db::name("cms_".$this->ModelInfo["table_name"]."_data")->find($id);
            $r=array_merge($index,$data);
        }else{
            $this->error("缺少参数");
        }
        //
        if(!$r){$this->error("未找到数据");}
        View::assign("r",$r);
        //
        $resultData=[];
        foreach($r as $key=>$v){
            if(!strstr($this->ModelInfo["is_enter"],",".$key.",")){continue;}
            $where["table_id"]=$this->ModelInfo["table_id"];
            $where["field"]=$key;
            $field=$this->TableFieldModel->where($where)->find();
            //
            $resultData[]=[
                "name"=>$field["name"]?$field["name"]:$key,
                "field"=>$key,
                "formtype"=>$field["formtype"],
                "defaultval"=>$field["defaultval"],
                "value"=>$v,
            ];
        }
        View::assign("data",$resultData);
        //判断是否有自定义列表模板
        if(file_exists($this->ModelViewPath."view.html")){
            return View::fetch($this->ModelViewPath."view.html");
        }else{
            return View::fetch();
        }
    }
    //调用前台模板预览
    public function view2(){
        $cache_id=Request::param("cache_id",0,"intval");
        if($cache_id){
            $cache=Db::name("cms_cache")->find($cache_id);
            $cache= json_decode($cache['data'],true);
            $r=array_merge($cache['index'],$cache['data']);
        }else{
            $this->error("缺少参数");
        }
        //
        if(!$r){$this->error("未找到数据");}
        View::assign($r);
        if($this->r["viewtemp"]){
            $viewtemp=$this->r["viewtemp"];
        }else{
            $viewtemp=$this->cat["viewtemp"];
        }
        return View::fetch(base_path().'data/templateFile/'.$viewtemp.".html");
    }
    //
    public function add(){
        if(!check_user_cat("info_add",$this->catid)){
            $this->error("您没有操作权限");
        }
        if(request()->isPost()){
            $result=$this->save("add");
            if($result["id"]){
                $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$result["id"],$this->request->param());
            }else{
                $this->UserLogModel->add(Request()->action(),"cms_cache",$result["cache_id"],$this->request->param());
            }
            $this->success("保存成功","",$result);
        }else{
            View::assign("pubid",make_pubid());
            //判断是否有自定义列表模板
            if(file_exists($this->ModelViewPath."add.html")){
                return View::fetch($this->ModelViewPath."add.html");
            }else{
                return View::fetch();
            }
        }
    }
    public function update(){
        if(!check_user_cat("info_editor",$this->catid)){
            $this->error("您没有操作权限");
        }
        if(request()->isPost()){
            //
            $result=$this->save("update");
            if($result["id"]){
                $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$result["id"],$this->request->param());
            }else{
                $this->UserLogModel->add(Request()->action(),"cms_cache",$result["cache_id"],$this->request->param());
            }
            $this->success("保存成功","",$result);
        }else{
            $id=Request::param("id",0,"int");
            $cache_id=Request::param("cache_id",0,"int");
            if($id){
                $r=$this->model->find($id)->toArray();
                //副表数据合并
                $data=Db::name("cms_".$this->ModelInfo["table_name"]."_data")->find($id);
                if($data){
                    $r=array_merge($r,$data);
                }
            }else if($cache_id){
                View::assign("cache_id",$cache_id);
                $cache=Db::name("cms_cache")->find($cache_id);
                $cache_data= json_decode($cache["data"],true);
                $r=array_merge($cache_data['index'],$cache_data['data']);
            }else{
                $this->error("缺少id参数");
            }
            if(!$r){$this->error("信息不存在");};

            //防止在某些情况下没有pubid
            $r["pubid"]=$r["pubid"]?$r["pubid"]:make_pubid();
            //
            View::assign("r",$r);
            //判断是否有自定义列表模板
            if(file_exists($this->ModelViewPath."update.html")){
                return View::fetch($this->ModelViewPath."update.html");
            }else{
                return View::fetch();
            }
        }
    }
    private function save($type){
        $data=$this->request->param();
        //验证
        //除了存草稿不需要验证信息，其它动作都需要验证信息
        if($data["action_type"]!="draft"){
            $this->dataCheck($data,$type);
        }
        //检测titleurl是否合格
        if($data['titleurl']){
            if(!preg_match("/^\/[\w|\/|\-]+\.html$/i", $data['titleurl'])){
                $this->error("自定义链接格式错误，只能使用[数字，字母，_，- ，/],并以/开头.html结尾");
            }
        }
        //数据加工处理(返回的包括主表和副表的数据)
        $CreateData=$this->dataCreate($data,$type);
        //先存到缓存表里
        if($data["action_type"]=="draft"){
            //放到缓存表并且将状态设置为【草稿】
            $cache_id=$this->model->saveCache($CreateData,"draft");
        }else{
            //提交审核
            $cache_id=$this->model->saveCache($CreateData,"readyCheck");
            //系统是否自动审核
            if($this->ModelInfo["autochecked"]){
                $id=$this->model->setCheckCache($cache_id);
            }else{
                if($data['id']){
                    //删除主表和data表
                    $this->model->where("id",$data['id'])->delete();
                    Db::name("cms_".$this->ModelInfo["table_name"]."_data")->delete($data['id']);
                }
            }
        }
        //更新路由
        $this->RouteModel->updateInfoRoute();//更新路由
        //
        return ["cache_id"=>$cache_id,"id"=>$data['id']];
    }
    //数据校验
    private function dataCheck($data,$type="add"){
        //录入项
        $is_enter=$this->ModelInfo["is_enter"];
        $is_enter_arr=explode(",",trim($is_enter,","));
        //
        $where=[];
        $where[]=["table_id","=",$this->ModelInfo["table_id"]];
        $where[]=["field","in",$is_enter_arr];
        $fieldarr=$this->TableFieldModel->where($where)->select()->toArray();
        foreach($fieldarr as $v){
            //必填项(不能为空验证)
            if(strstr($this->ModelInfo["must_enter"],",".$v['field'].",")){
                //echo $v['field'];
                //判断是不是checkbox,如果是执行函数验证
                if($v['formtype']=="checkbox"){
                    $this->validate->message[$v['field'].".require"]=$v['name']."必须勾选!";
                    $this->validate->rule[$v['field']][]="require";
                }
                //判断是不是多图上传
                elseif($v['formtype']=="morepic"){
                    $this->validate->message[$v['field']."_smallimg.require"]="请上传".$v['name']."!";
                    $this->validate->rule[$v['field']."_smallimg"][]="require";
                }
                else{
                    $this->validate->message[$v['field'].".require"]="请填写".$v['name']."!";
                    $this->validate->rule[$v['field']][]="require";
                }
            }
            //正则验证
            if($v['pattern']){
                $this->validate->message[$v['field'].".regex"]=$v['errortips']?$v['errortips']:$v['name']."验证不通过!";
                $this->validate->regex[$v['field']."_regex"]=$v['pattern'];
                $this->validate->rule[$v['field']]["regex"]=$v['field']."_regex";
            }
            //值维一验证
            if($v['isunique']){
                $this->validate->message[$v['field'].".unique"]=$v['name']."对应的记录已存在!";
                $tableName=$v['issystem']?"cat":"cat_data";
                if($type=="add"){
                    $this->validate->rule[$v['field']]["unique"]=$tableName;
                }else{
                    //排除自己
                    $this->validate->rule[$v['field']]["unique"]=$tableName.",".$v['field'].",".$data["catid"];
                }
            }
        }
        //
        if(!$this->validate->check($data)){
            $this->error($this->validate->getError());
        }
    }
    public function dataCreate($data,$type="add"){//$type为添加来源，add:后台添加 update:后台修改 import_add:导入[增加] import_update:导入[修改]
        $return=["index"=>[],"data"=>[]];
        //录入项
        $is_enter=$this->ModelInfo["is_enter"];
        $is_enter_arr=explode(",",trim($is_enter,","));
        //
        $where=[];
        $where[]=["table_id","=",$this->ModelInfo["table_id"]];
        $where[]=["field","in",$is_enter_arr];
        $fieldarr=$this->TableFieldModel->where($where)->select();
        foreach($fieldarr as $v){
            //如果是导入的，判断这个字段是否在导入的数据里存在，如果不存在不做下一步处理
            if(($type=="import_add"||$type=="import_update")&&!isset($data[$v['field']])){
                continue;
            }
            //复选框 多选下拉
            if($v['formtype']=="checkbox"||$v['formtype']=="selects"){
                //为数据导入的时候，表格里填写的是:上网|听音乐|打游戏 只要两边增加|即可
                if($type=="import_add"||$type=="import_update"){
                    if($data[$v['field']]){
                        $data[$v['field']]="|".$data[$v['field']]."|";
                    }
                }else{
                    $data[$v['field']]=implode("|",$data[$v['field']]);
                    if($data[$v['field']]){
                        $data[$v['field']]="|".$data[$v['field']]."|";
                    }
                }
            }
            //多图上传
            if($v['formtype']=="morepic"){
                $morepic_str="";
                $smallimg=$data[$v['field']."_smallimg"];
                $bigimg=$data[$v['field']."_bigimg"];
                $imgname=$data[$v['field']."_imgname"];
                foreach($smallimg as $key=>$val){
                    $morepic_str.=$smallimg[$key]."||".$bigimg[$key]."||".$imgname[$key]."\r\n";
                }
                $morepic_str=trim($morepic_str,"\r\n");
                $data[$v['field']]=$morepic_str;
            }
            //多值字段
            if($v['formtype']=="morevalue"){
                $morevalue_str="";
                $fieldLen=$data[$v['field']."_morevalue_len"];//获取一共有多少列字段
                $fieldValArr=array();
                foreach($fieldLen as $k1=>$v1){
                    $fieldValArr[$k1]=$data[$v['field']."_".$k1];
                }
                //根据第一列字段，提取有多个行数据,并循环
                foreach($fieldValArr[0] as $k2=>$v2){
                    //单个信息
                    $row_str="";
                    foreach($fieldValArr as $k3=>$fieldVal){
                        if($k3>0){
                            $row_str.="{{FieldSplit}}".$fieldVal[$k2];
                        }else{
                            $row_str=$fieldVal[$k2];
                        }
                    }
                    //多行信息拼接
                    if($morevalue_str){
                        $morevalue_str.="{{RsSplit}}".$row_str;
                    }else{
                        $morevalue_str=$row_str;
                    }
                }
                $data[$v['field']]=$morevalue_str;
            }
            //日期
            if($v['formtype']=="date"){
               $data[$v['field']]=$data[$v['field']]?strtotime($data[$v['field']]):"";
            }
            //如果是编辑器字段截取内容做为简介
            if($v['formtype']=="editor"||$v['formtype']=="tiny"){
                //如果开启了远程保存图片的话
                if($data[$v['field']."_saveFile"]){
                    $SaveRemoteImg=new \app\admin\model\SaveRemoteImgModel();
                    $data[$v['field']]=$SaveRemoteImg->doIt(htmlspecialchars_decode($data[$v['field']]));
                }
                //如果开启了提取第一张图做为缩略图并且缩略图为空的话
                if($data[$v['field']."_getFirstImg"]&&!$data["thumb"]){
                    $return["index"]["thumb"]=$this->getFirstImg($data[$v['field']]);
                }
                //提取简介
                if(!$data['description']){
                    $data['description']= mb_substr(strip_tags($data[$v['field']]),0,config("setting.description_len"),'utf-8');
                }
            }
            //判断是否为 int smallint tinyint bigint
            if(in_array($v['fieldtype'],array("tinyint","smallint","int","bigint"))){
               $data[$v['field']]=abs($data[$v['field']]);//禁止出现负数
            }
            //保息信息处理函数
            if($v['savefun']&&strstr($v['savefun_trigger'],"|".$type."|")){
                $savefunArr=explode("###",$v['savefun']);
                $funVal=array();
                if($savefunArr[1]){
                    $funParmas=explode(",",$savefunArr[1]);
                    $funVal=array_merge(array($data[$v['field']]),$funParmas);
                }else{
                    $funVal=array($data[$v['field']]);
                }
                $data[$v['field']]=call_user_func_array($savefunArr[0],$funVal);
            }
           //检测是不是副表字段
             if($v['issystem']){
                $return["index"][$v['field']]=$data[$v['field']];
            }else{
                $return["data"][$v['field']]=$data[$v['field']];
            }
        }
        //系统字段
        $default_field=["id","cache_id","catid","modelid","pagetitle","keywords","description","titleurl","link","pubid","sort","userid","username","addtime","editortime","views","is_good","is_top","favs","viewtemp"];
        $data["modelid"]=$this->ModelInfo["modelid"];
        $data["userid"]=$this->user_id;
        $data["username"]=$this->username;
        $data["addtime"]=time();
        $data["editortime"]=time();
        foreach($default_field as $field){
            if(isset($data[$field])){
                $return["index"][$field]=$data[$field];
            }
        }
        return $return;
    }
    //删除
    public function delete(){
        if(!check_user_cat("info_delete",$this->catid)){
            $this->error("您没有操作权限");
        }
        $ids=Request::param("ids");
        $cache_ids=Request::param("cache_ids");
        if($ids){
            $this->model->DeleteIndex($ids);
            $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
        }else if($cache_ids){
            $this->model->DeleteCache($cache_ids);
            $this->UserLogModel->add(Request()->action(),"cms_cache",$cache_ids,$this->request->param());
        }else{
            $this->error("请勾选要操作的信息");
        }
        $this->RouteModel->updateInfoRoute();//更新路由
        $this->success("删除成功");
    }
    //发布
    public function push(){
        $ids=Request::param("ids");
        if($ids){
            $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
        }else if($cache_ids){
            $this->UserLogModel->add(Request()->action(),"cms_cache",$cache_ids,$this->request->param());
        }else{
            $this->error("请勾选要操作的信息");
        }
        Db::name("cms_".$this->ModelInfo["table_name"])->update([
            "id"=>$ids,
            "push_time"=>time(),
            'state'=>1,
        ]);
        $this->success("发布成功");
    }
    //字段排序
    public function updateSort(){
        $id=Request::param("id");
        $sort=Request::param("sort");
        foreach($id as $key=>$vid){
            $data['id']=(int)$vid;
            $data['sort']=(int)$sort[$key];
            Db::name("cms_".$this->ModelInfo["table_name"])->update($data);
        }
        $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
        $this->success("排序更改成功");
    }
    //审核通过
    public function checked(){
        if(!check_user_cat("info_checked",$this->catid)){
            $this->error("您没有操作权限");
        }
        $ids=Request::param("cache_ids");
        if($ids){
            foreach($ids as $id){
                $this->model->setCheckCache($id);
            }
            $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
        }else{
            $this->error("请勾选要操作的信息");
        }
        $this->success("审核成功");
    }
    //审核不通过
    public function unChecked(){
        if(!check_user_cat("info_checked",$this->catid)){
            $this->error("您没有操作权限");
        }
        $ids=Request::param("cache_ids");
        $remark=Request::param("remark");
        if($ids){
            Db::name("cms_cache")->where([
                ["cache_id","in",$ids]
            ])->update([
                "state"=>"notCheck",
                "remark"=>$remark,
            ]);
            $this->success("审核不成功操作成功");
        }else{
            $this->error("请勾选要操作的信息");
        }
    }
    //取消审核
    public function cancelChecked(){
        if(!check_user_cat("info_checked",$this->catid)){
            $this->error("您没有操作权限");
        }
        $ids=Request::param("ids");
        if($ids){
            foreach($ids as $id){
                $this->model->IndexToCache($id,"readyCheck");
            }
            $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
        }else{
            $this->error("请勾选要操作的信息");
        }
        $this->success("操作成功，状态为[待审核]");
    }
    //提交审核
    public function submitChecked(){
        $ids=Request::param("cache_ids");
        if($ids){
            Db::name("cms_cache")->where([
                ["cache_id","in",$ids]
            ])->update([
                "state"=>"readyCheck",
            ]);
            $this->success("操作成功");
        }else{
            $this->error("请勾选要操作的信息");
        }
    }
    //置顶
    public function set_top(){
        $ids=Request::param("ids");
        $value=Request::param("value",0,"intval");
        if(!$ids){$this->error("请勾选信息！");};
        foreach($ids as $key=>$vid){
            $data=[];
            $data['id']=(int)$vid;
            $data['is_top']=$value;
            Db::name("cms_".$this->ModelInfo["table_name"])->update($data);
        }
        $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
        $this->success("置顶操作成功");
    }
    //推荐
    public function set_good(){
        $ids=Request::param("ids");
        $value=Request::param("value",0,"intval");
        if(!$ids){$this->error("请勾选信息！");};
        foreach($ids as $key=>$vid){
            $data=[];
            $data['id']=(int)$vid;
            $data['is_good']=$value;
            Db::name("cms_".$this->ModelInfo["table_name"])->update($data);
        }
        $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
        $this->success("推荐操作成功");
    }
    //复制信息
    public function copy(){
        if(request()->isPost()){
            $ids=Request::param("ids");
            if(!$ids){
                $this->error("请选择信息");
            }
            $catid=Request::param("target_catid","intval",0);
            if(!$catid){
                $this->error("请选择目标栏目");
            }
            $data=Db::name("cms_".$this->ModelInfo["table_name"])->where(array(
                ["id","in",$ids]
            ))->select();
            foreach($data as $v){
                $oldId=$v["id"];
                $fbData=Db::name("cms_".$this->ModelInfo["table_name"]."_data")->find($oldId);
                //主表插入
                unset($v["id"]);
                unset($v["titleurl"]);
                $v["catid"]=$catid;
                $id=Db::name("cms_".$this->ModelInfo["table_name"])->insertGetId($v);
                //副表插入
                $fbData=Db::name("cms_".$this->ModelInfo["table_name"]."_data")->find($oldId);
                $fbData["id"]=$id;
                Db::name("cms_".$this->ModelInfo["table_name"]."_data")->insert($fbData);
            }
            $this->model->updateInfoNum($catid);
            $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
            $this->success("操作成功");
        }else{
            View::assign("cat",$this->model->selfModelCat());
            View::assign("catid",Request::param("catid",0,"intval"));
            View::assign("ids",Request::param("ids"));
            return View::fetch();
        }
    }
    //移动信息
    public function move(){
        if(request()->isPost()){
            $ids=Request::param("ids");
            if(!$ids){
                $this->error("请选择信息");
            }
            $catid=Request::param("target_catid","intval",0);
            if(!$catid){
                $this->error("请选择目标栏目");
            }
            $data=Db::name("cms_".$this->ModelInfo["table_name"])->where(array(
                ["id","in",$ids]
            ))->select();
            foreach($data as $v){
                $update=[];
                $update["id"]=$v['id'];
                $update["catid"]=$catid;
                Db::name("cms_".$this->ModelInfo["table_name"])->update($update);
            }
            $this->model->updateInfoNum($this->catid);
            $this->model->updateInfoNum($catid);
            $this->UserLogModel->add(Request()->action(),"cms_".$this->ModelInfo["table_name"],$ids,$this->request->param());
            $this->success("操作成功");
        }else{
            View::assign("cat",$this->selfModelCat());
            View::assign("catid",Request::param("catid",0,"intval"));
            View::assign("ids",Request::param("ids"));
            return View::fetch("copy");
        }
    }
    //栏目分类
    public function getCat($pid){
        $catstr=$this->forCat($pid);
        return $catstr;
    }
    protected function forCat($pid=0,$str=""){
        $where["pid"]=$pid?$pid:0;
        $where["status"]=1;
        $cat=Db::name("cat")->where($where)->order("sort asc,catid asc")->select();
        if(count($cat)>0){
            foreach($cat as $v){
                if(!check_user_cat("info_view",$v['catid'])){
                    continue;
                }
                $nbsp_str="";
                for($i=1;$i<$v[level];$i++){
                    $nbsp_str.="&nbsp;&nbsp;";
                }
                if($this->catid&&$this->catid==$v['catid']){
                    $this_selected="selected";
                }else{
                    $this_selected="";
                }
                $str.="<option value='{$v['catid']}' ".$this_selected.">{$nbsp_str}|-{$v['name']}</option>";
                $str=$this->forCat($v['catid'],$str);
            }
            return $str;
        }else{
            return $str;
        }
    }
    //整站所有相同模型的栏目（用在 信息移动，复制页面里的）
    private function selfModelCat($pid=0,$str=""){
        $where["pid"]=$pid;
        $where["status"]=1;
        $cat=Db::name("cat")->field("catid,level,name,modelid,status,sort,pid")->where($where)->order("sort asc,catid asc")->select();
        if(count($cat)>0){
            foreach($cat as $v){
                $nbsp_str="";
                for($i=1;$i<$v['level'];$i++){
                    $nbsp_str.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                if($v["modelid"]!=$this->modelid){
                    $this_selected="disabled";
                    $disabled_str="(<b>模型不同</b>)";
                }else{
                    $this_selected="";
                    $disabled_str="";
                }
                $str.="<option value='{$v['catid']}' ".$this_selected.">{$nbsp_str}|-{$v['name']} $disabled_str</option>";
                $str=$this->selfModelCat($v['catid'],$str);
            }
            return $str;
        }else{
            return $str;
        }
    }
    //导出
    public function export(){
        if(request()->isPost()){
            $where=[];
            $prefix=config('database.connections.mysql.prefix');
            $export_field=Request::param('export_field');
            if(Request::param('export_type')=="check"){
                $ids=explode(",",trim(Request::param('ids'),","));
                if(!trim(Request::param('ids'),",")){$this->error("请勾选要导出的信息");}
                $where[]=[$prefix."cms_".$this->ModelInfo["table_name"].'.id',"IN",$ids];
            }
            //
            $where[]=['catid',"IN",getSonCat($this->catid)];
            $order="sort asc,is_top desc,is_good desc,newstime desc,".$prefix."cms_".$this->ModelInfo["table_name"].".id desc";//默认排序方式
            $data=Db::name("cms_".$this->ModelInfo["table_name"])->join($prefix."cms_".$this->ModelInfo["table_name"]."_data",$prefix."cms_".$this->ModelInfo["table_name"].".id=".$prefix."cms_".$this->ModelInfo["table_name"]."_data.id")->where($where)->order($order)->select();
            //
            $where=[];
            $where[]=["field","in",$export_field];
            $where[]=["table_id","=",$this->ModelInfo["table_id"]];
            //系统字段
            $default_field=[];
            if(in_array("id",$export_field)){
                $default_field[]=["name"=>"id","field"=>"id"];
            }
            if(in_array("catid",$export_field)){
                $default_field[]=["name"=>"catid","field"=>"catid"];
            }
            //
            $fieldArr=$this->TableFieldModel->field("name,field,formtype")->where($where)->order("sort asc,field_id asc")->select()->toArray();
            $fieldArr=array_merge($default_field,$fieldArr);
            //
            $objPHPExcel = new \PHPExcel();
            $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);  //设置保存版本格式
            //接下来就是写数据到表格里面去
            $objActSheet = $objPHPExcel->getActiveSheet(0);
            //表头
            foreach($fieldArr as $k=>$v){
                $objActSheet->setCellValue(IntToChr($k).'1', $v["name"]);
            }
            //内容
            foreach($data as $k1=>$v){
                foreach($fieldArr as $k2=>$fi){
                    if($fi["formtype"]=="date"){
                        $value=date("Y-m-d H:i:s",$v[$fi["field"]]);
                    }else{
                        $value=$v[$fi["field"]];
                    }
                    $objActSheet->setCellValue(IntToChr($k2).($k1+2),$value);
                }
            }
            $filename="./upload/cache/export_excel_cahce/".date("YmdHis")."-".rand(1000,9999).'.xls';
            $objWriter->save($filename);
            $this->success(trim($filename,"."));
        }else{
            //查询模型下的字段
            $formtype_arr=explode("\r\n",$this->ModelInfo['formtemp']);
            $modelField=array();
            $modelAllField[]=["field"=>"id","name"=>"id"];
            $modelAllField[]=["field"=>"catid","name"=>"catid"];
            foreach($formtype_arr as $v){
                $f=explode("<!--field-->",$v);
                $modelAllField[]=["field"=>$f[1],"name"=>$f[0]];
            }

            View::assign("modelAllField",$modelAllField);//模型所有字段，包括主表和副表的（用于导入数据的时候选择要哪些字段）
            return View::fetch();
        }
    }
    //提取内容第一张图做为缩略图
    private function getFirstImg($str){
        preg_match("/\<[img|IMG].*?src=\"(.+?)\".*?>/",$str,$result);
        return $result[1];
    }
}
